import React from 'react';
import ReactDOM from 'react-dom';
import { observer } from 'mobx-react';
import { ViewResourceProps } from '.';
import moment from 'moment';
import {
  WeaDateSwitch,
  WeaNewScroll,
  WeaInputSearch,
  WeaRightMenu,
  WeaDialog,
  WeaLocaleProvider,
  WeaDragChoose
} from 'ecCom';
import { Tooltip, Spin, Button } from 'antd';
import { toJS } from 'mobx';
import List from '../../components/list';
import { getCurrentDate } from '../../apis/resource';
import jQuery from 'jquery';
import { InnerTabCard } from '../../components/card';
import ViewResourceSearch from "./ViewResourceSearch";
const getLabel = WeaLocaleProvider.getLabel;

if (WeaLocaleProvider.getUserLanguage() == 7 || WeaLocaleProvider.getUserLanguage() == 9) {
  moment.locale('zh-cn');
} else {
  moment.locale('en');
}

@observer
export default class ViewResouceContainer extends React.Component<ViewResourceProps, any> {

  constructor(props) {
    super(props);
    this.state = {
      date: new Date(),
      foucsInput: false,
    }
    getCurrentDate({}).then(({ currentDate }) => {
      this.setState({ date: currentDate });
    });
  }

  componentDidUpdate(prevProps, prevState) {
    this.createHeight();
    const { cubeViewResource, Search } = this.props;
    setTimeout(() => {
      if (cubeViewResource.windowTitle != '') {
        document.title = cubeViewResource.windowTitle;
      }
    }, 500);
    Search.isInnerTab = true;
  }

  componentWillReceiveProps() {
    const { cubeViewResource } = this.props;
    this.setState({ date: cubeViewResource.currentdate });
    cubeViewResource.timeType = 'day';
  }

  /*判断拖拽中的每个块是否激活*/
  checkDragActive = (itemProps, dragState) => {
    let { room, itemPosition } = itemProps, { startProps = {} } = dragState, startRoom = startProps.room || {}
    if (startRoom.id && room.id == startRoom.id) {
      let { minRow, minColumn, maxRow, maxColumn } = dragState
      return itemPosition[0] >= minRow && itemPosition[0] <= maxRow && itemPosition[1] >= minColumn && itemPosition[1] <= maxColumn
    }
    return false
  }

  createHeight = () => {
    const { cubeViewResource } = this.props;
    // 处理高度自适应问题
    let
      container = jQuery('.resource-container', ReactDOM.findDOMNode(this)),
      conHeight = this.props.height ? (this.props.height - 108) : container.height();
    let listHeight;
    let tab = jQuery('.resource-plan-tab', container), tabHeight = tab.height()
    if (cubeViewResource.showMoreVisible) {
      tabHeight = tabHeight + 40;
    }
    if (tabHeight >= (conHeight / 2)) {
      listHeight = (conHeight / 2);
      tabHeight = (conHeight / 2);
    } else {
      listHeight = conHeight - tabHeight;
    }
    cubeViewResource.updateHeight(conHeight, tabHeight, listHeight);
  }

  doRightMenuAction = (key) => {
    const { cubeViewResource } = this.props;
    if (key == 'add') {
      cubeViewResource.onAdd();
      return;
    }
    const d = new Date();
    cubeViewResource.currentdate = cubeViewResource.currentdate.split(' ')[0] + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
    cubeViewResource.timeType = key;
    this.onChangeWeaDateSwitch(key, cubeViewResource.currentdate, null);
  }

  /*周月日组件切换回调 */
  /**
   * 说明：若日,传点前的日期，且给值movedate，若年或月则传点击后的日期，且movedate不给值
   */
  onChangeWeaDateSwitch = (type, date, range) => {
    const { cubeViewResource } = this.props;
    const { timeType } = cubeViewResource;
    type != timeType && cubeViewResource.updateTimeType(type);
    cubeViewResource.resourceId = '';
    let movedate = '';
    let bywhat = '4';
    if (typeof date != 'string' && date._d && date._i) {
      if (typeof date._d == 'string') {
        date._d = new Date(date._d);
      }
      if (typeof date._i == 'string') {
        date._i = new Date(date._i);
      }
      if (date._d.getTime() != date._i.getTime() && type == 'day') {//说明点击箭头切换日期
        if (date._d.getTime() < date._i.getTime()) {
          movedate = '-1';
        } else {
          movedate = '1';
        }
      }
    }
    switch (type) {
      case 'year':
        bywhat = '1';
        break;
      case 'month':
        bywhat = '2';
        break;
      case 'week':
        bywhat = '3';
        break;
      case 'day':
        bywhat = '4';
        break;
    }
    let currentdate;
    if (typeof date == 'string') {
      currentdate = date;
    } else if (typeof date._i == 'string') {
      currentdate = bywhat == '4' ? date._i : date._d;
    } else {
      let rightdate;
      if (date._i && date._d) {
        rightdate = bywhat == '4' ? date._i : date._d;
      } else {
        rightdate = date;
      }
      let m = rightdate.getMonth() + 1 + '';
      let d = rightdate.getDate() + '';
      if (m.length == 1) m = '0' + m;
      if (d.length == 1) d = '0' + d;
      currentdate = rightdate.getFullYear() + '-' + m + '-' + d;
    }
    this.setState({ date: date });
    cubeViewResource.query({ bywhat, movedate, currentdate });
  }

  getTableHeaderInfo = (timeType, date, startHour, endHour) => {
    let blockNum = 0, tableTitle = '', tableHeaders: any = [];
    if (moment.isMoment(date)) date = new Date(date.format('L'));
    let curmoment = moment(date);
    if (timeType == 'day') {
      blockNum = endHour - startHour + 1
      tableTitle = curmoment.format(`M${getLabel(383373, '月')}D${getLabel(383374, '日').replace('-', '')}(ddd)${getLabel(33425, '单位')}:`) + getLabel(383376, '时')
      tableTitle = this.modifyWeekName(tableTitle);
      for (startHour; startHour <= endHour; startHour++)
        tableHeaders.push(startHour);
    } else if (timeType == 'week') {
      const { cubeViewResource } = this.props;
      const { weekstart } = cubeViewResource;
      blockNum = 7;
      let start = weekstart == '2' ? 1 : 0;
      tableTitle = curmoment.format(`YYYY${getLabel(383372, '年')}ww`) + getLabel(383377, '周')
      for (var i = start; i < (start + 7); i++) {
        let titleTemp = curmoment.day(i).format(`MM${getLabel(383373, '月')}DD${getLabel(383374, '日').replace('-', '')}(ddd)`);
        titleTemp = this.modifyWeekName(titleTemp);
        tableHeaders.push(titleTemp)
      }
    } else {
      blockNum = curmoment.daysInMonth()
      tableTitle = curmoment.format(`YYYY${getLabel(383372, '年')}MM${getLabel(383373, '月').replace('-', '')}`) + `(${blockNum}${getLabel(383378, '天')})`
      for (var i = 1; i <= blockNum; i++)
        tableHeaders.push(i);
    }
    return { blockNum: blockNum, tableTitle: tableTitle, tableHeaders: tableHeaders }
  }

  /*周显示多语言修正 ，moment打包后中文失效*/
  modifyWeekName = (name) => {
    try {
      if (WeaLocaleProvider.getUserLanguage() == 7 || WeaLocaleProvider.getUserLanguage() == 9) {
        name = name.replace("Sun", "周日");
        name = name.replace("Mon", "周一");
        name = name.replace("Tue", "周二");
        name = name.replace("Wed", "周三");
        name = name.replace("Thu", "周四");
        name = name.replace("Fri", "周五");
        name = name.replace("Sat", "周六");
      }
    } catch (Exception) {
    }
    return name;
  }

  /*创建面板使用情况的每一行得td*/
  createTdList = (resource, blockNum, rowNum) => {
    const { cubeViewResource } = this.props;
    const { timeType, duration, useMap, weekstart } = cubeViewResource;
    let tdList: any = [];
    let useArray = useMap[resource.id];
    // 创建冲突的、带有提示的单元格
    let createTooltipTd = function (obj, otherProps = {}, width?) {
      let { content, bgcolor, fontcolor, title } = obj;
      let style: any = { backgroundColor: bgcolor || '#AFDC9E', color: fontcolor || '#000', textAlign: 'center' };
      let td = (
        <Tooltip title={createTitle(toJS(title))} placement="bottomRight">
          <td style={width && { width: width }} {...{ conflict: true }} {...otherProps}>
            <div style={{ ...style, width: '100%', height: '100%' }}>
              <div className="resource-td-modal" />
              {content > 1 && content}</div>
          </td>
        </Tooltip>
      );
      return td;
    };
    if (timeType == 'week' || timeType == 'month') {
      for (let i = 0; i < blockNum; i++) {
        tdList.push(<td>
          <div className="resource-td-modal " />
        </td>);
      }
      if (!useArray || useArray.length == 0) {
        return tdList;
      }
      useArray.forEach((obj) => {
        let objDate = moment(obj.date);
        let tdIdx = timeType == 'week' ? objDate.day() : objDate.date() - 1;
        if (timeType == 'week' && weekstart == '2') {//周一为开始
          tdIdx = tdIdx == 0 ? 6 : tdIdx - 1;
        }
        if (tdIdx < 0 || tdIdx >= blockNum) return;
        if (timeType == 'month') {//不是当前月的数据过滤掉，避免覆盖数据
          let { date } = this.state;
          if (moment.isMoment(date)) date = new Date(date.format('L'));
          let curmoment = moment(date);
          if (curmoment.year() != objDate.year() || curmoment.month() != objDate.month()) return;
        }
        tdList[tdIdx] = createTooltipTd(obj);
      });
      return tdList;
    } else {
      return this.createTdListInDay(duration, useArray, resource, createTooltipTd, rowNum, tdList);
    }

  }

  /*创建时间类型为天时的单元格*/
  createTdListInDay(duration, useArray, room, createTooltipTd, rowNum, tdList) {
    const { cubeViewResource } = this.props;
    let { startHour, endHour, dspunit } = cubeViewResource;
    let useBlockMap = {};//已被使用的块，数据结构：小时数:{变色的序号：{背景颜色，字体颜色，内容}，...}
    // let subNum = 1;//每小时会被分成几段
    // 生成已被占用的时间段
    useArray && useArray.forEach((obj) => {
      // 时间处理，确认序号
      if (!obj.time) return;
      let time = obj.time.split(':');
      if (time.length != 2) return;
      let hour = parseInt(time[0]), minute = parseInt(time[1]);
      let idx = duration > 0 ? Math.floor(minute / duration) : 0;
      // 找到该数据对应的存储位置。
      if (!useBlockMap[hour]) useBlockMap[hour] = {};
      let useHour = useBlockMap[hour];
      useHour[idx] = obj;
    });
    let width = (100 / dspunit) + "%";
    /*创建每小时内的分隔块、即第二层td的方法*/
    let createSubTd = (hour, idx, rowNum, colNum) => {
      let startMinute = idx * duration, endMinute = startMinute + duration - 1;
      let startTime = (hour > 9 ? hour : '0' + hour) + ':' + (startMinute > 9 ? startMinute : '0' + startMinute),
        endTime = (hour > 9 ? hour : '0' + hour) + ':' + (endMinute > 9 ? endMinute : '0' + endMinute);
      // 有值则说明已被占用
      if (useBlockMap[hour] && useBlockMap[hour][idx]) {
        return createTooltipTd(useBlockMap[hour][idx], {
          itemPosition: [rowNum, colNum],
          startTime,
          endTime,
          room
        }, width);
      }
      // 空时段
      return (
        <td style={{ width: width }} {...{ itemPosition: [rowNum, colNum] }} {...{ startTime, endTime, room }}>
          <div className="resource-td-modal" />
        </td>
      );
    };

    // 生成第一层td列表
    let colNum = 0;
    for (startHour; startHour <= endHour; startHour++) {
      let subTdList: any = [];
      for (let i = 0; i < dspunit; i++) {
        subTdList.push(createSubTd(startHour, i, rowNum, colNum))
        colNum++;
      }
      let td = (
        <td>
          <table className="resource-subTable">
            <tr>{subTdList}</tr>
          </table>
        </td>
      );
      tdList.push(td);
    }
    return tdList;
  }

  render() {
    const { Search, cubeViewResource } = this.props;
    const { loading, resourcesList, timeType, card, createUrl } = cubeViewResource;
    const { resourceId } = cubeViewResource;
    // 列表中使用的数据
    let { date } = this.state
    let { startHour, endHour } = cubeViewResource;
    let { blockNum, tableTitle, tableHeaders } = this.getTableHeaderInfo(timeType, date, startHour, endHour);
    let tableContent = (
      <table className="resource-plan-tab">
        <tbody>
          {!loading && (resourcesList && resourcesList.length > 0) &&
            resourcesList.map((resource, index) => {
              let tdList = this.createTdList(resource, blockNum, index);
              let tdClass = resourceId == resource.id ? 'resource-name cur' : 'resource-name';
              return (
                <tr className={index == 0 ? 'no-border-top' : ''}>
                  <Tooltip placement="right" title={<div dangerouslySetInnerHTML={{ __html: resource.title }} />} >
                    <td onClick={() => {
                      if (resourceId == '') {
                        cubeViewResource.resourceId = resource.id
                        cubeViewResource.search({
                          ...cubeViewResource.searchParam,
                          datasqlwhere: cubeViewResource.searchParam.datasqlwhere + ' and t1.' + cubeViewResource.resourceFieldName + '=\'' + resource.id + '\''
                        });
                      } else {
                        if (resourceId == resource.id) {
                          cubeViewResource.resourceId = '';
                          cubeViewResource.search(cubeViewResource.searchParam);
                        } else {
                          cubeViewResource.resourceId = resource.id
                          cubeViewResource.search({
                            ...cubeViewResource.searchParam,
                            datasqlwhere: cubeViewResource.searchParam.datasqlwhere + ' and t1.' + cubeViewResource.resourceFieldName + '=\'' + resource.id + '\''
                          });
                        }
                      }
                    }} className={tdClass}>{resource.name}</td></Tooltip>
                  {tdList}
                </tr>
              );
            })
          }
        </tbody>
      </table>
    );
    // 高度控制
    const { tabHeight, spinisload } = this.props.cubeViewResource;
    let tabHeightValue, listHeightValue, spinisloadvalue;
    tabHeightValue = tabHeight - 36;
    // listHeightValue = listHeight;
    spinisloadvalue = spinisload;

    return (
      <div onClick={() => Search.showSlideModal(false, "", "")} className="wea-cube-resource-con f12" style={{ height: '100%' }}>
        <div className="resource-plan-top">
          {/* 资源面板的头部操作按钮 */}
          <div className="resource-plan-top-con line">
            {createUrl &&
              <Button onClick={() => { cubeViewResource.onAdd() }} style={{ marginRight: 10 }}>{getLabel(82, '新建')}</Button>
            }
            <WeaDateSwitch currentType={cubeViewResource.timeType} onChange={this.onChangeWeaDateSwitch}
              currentDay={this.state.date} weekFirstDay={cubeViewResource.weekstart == '2' ? 1 : 0} />
            <Tooltip placement="bottom" title={getLabel(354, '刷新')}>
              <span className="icon-coms-Refresh" style={{
                cursor: 'pointer', padding: '0 10px', color: '#B2B2B2',
                fontSize: '16px', display: 'inline-block', position: 'absolute', top: '15px'
              }}
                onClick={() => {
                  cubeViewResource.query(cubeViewResource.resourceParams);
                }} />
            </Tooltip>
          </div>
          {/* 资源面板的头部 */}
          <table className="resource-plan-tab-header">
            <tbody>
              <tr className="no-border-top">
                <th className="first align-center">{getLabel(124947, '资源面板')}</th>
                <th colSpan={blockNum}>{tableTitle || getLabel(383375, '读取中') + '...'}</th>
              </tr>
              {tableHeaders && tableHeaders.length > 0 && (
                <tr>
                  <th className="search">
                    <WeaInputSearch
                      value={this.state.roomName}
                      style={{
                        display: 'inline-block',
                        width: cubeViewResource.conditions && cubeViewResource.conditions.length > 0 ? 170 : '100%',
                        borderRight: '1px solid #eaeaea'
                      }}
                      placeholder={getLabel(197, '搜索') + '...'}
                      onFocusChange = {bool => {this.setState({foucsInput: bool})}}
                      onSearchChange={v => {
                        cubeViewResource.resourceParams['content'] = v;
                        // 点击x号刷新页面
                        if(v == '' && !this.state.foucsInput){ 
                          cubeViewResource.query({...cubeViewResource.resourceParams, content: v})
                        }
                      }}
                      onSearch={(v) => {
                        cubeViewResource.query({ ...cubeViewResource.resourceParams, content: v })
                      }}
                    />
                    <ViewResourceSearch cubeViewResource={cubeViewResource} Search={Search} />
                  </th>
                  {tableHeaders.map((header) => {
                    return (<th className="header">{header}</th>)
                  })}
                </tr>
              )}
            </tbody>
          </table>
        </div>

        <div className="resource-container">
          {loading && <div className="align-center" style={{ marginTop: 120 }}><Spin /></div>}
          {!loading && (!resourcesList || resourcesList.length == 0) && (

            <div className="resource-list-placeholder">
              <i className="anticon anticon-frown" style={{ marginRight: 4 }} />
              {getLabel(83553, '暂无数据')}
            </div>
          )}
          <Spin tip="" spinning={spinisloadvalue}>
            <div className="tab-container" style={{ height: tabHeightValue, minHeight: '130px' }}>
              <WeaRightMenu
                datas={cubeViewResource.rightMenus}
                onClick={this.doRightMenuAction}
                collectParams={{
                  "favname": getLabel(124947, '资源面板'),
                  "link": '/' + window.location.toString().split('/').slice(3).join('/'),
                  "favouritetype": 5,
                  "importantlevel": 1
                }}
              >
                <WeaNewScroll height="100%" ref="tabScroll" style={{}}>
                  {/* 资源面板使用情况的内容 */}
                  {timeType == 'day' && createUrl && createUrl != '' ? (
                    <WeaDragChoose ref={ref => cubeViewResource.dragref = ref} activeStyle={{ backgroundColor: '#E1ECFF' }}
                      onSelectEnd={cubeViewResource.dragChooseEnd} checkActive={this.checkDragActive}>
                      {tableContent}
                    </WeaDragChoose>
                  ) : tableContent}
                </WeaNewScroll>
              </WeaRightMenu>
            </div>
          </Spin>
          {!loading && (resourcesList && resourcesList.length > 0) && cubeViewResource.showMoreVisible &&
            <div onClick={() => {cubeViewResource.getMore()}} className="list-more">
              {getLabel('83704', '显示更多')}
            </div>}
          <div className="list-container" style={{ height: listHeightValue }}>
            <List Search={Search} />
          </div>
        </div>
        {
          (cubeViewResource.createUrl.indexOf("/spa/cube/index.jsp#/main/cube/card") > -1) ?
            // (cubeViewResource.visible &&
            <WeaDialog
              onCancel={() => { cubeViewResource.visible = false; cubeViewResource.query(cubeViewResource.resourceParams); }}
              title={card.cardTab.title || ' '}
              iconBgcolor={card.iconInfo.iconBg || "#96358a"}
              icon={card.iconInfo.icon || 'icon-coms-ModelingEngine'}
              iconFontColor={card.iconInfo.iconColor || "#fff"}
              visible={cubeViewResource.visible}
              hasScroll
              style={{ width: 1200, height: 700 }}
              buttons={cubeViewResource.quickButtons}
              destroyBodyOnClose={true}
            >
              <div className="coms-mode-docker coms-mode-card mode-card-resource mode-card-dialogshow" style={{ overflow: 'hidden', height: 700 }}>
                {cubeViewResource.visible && <InnerTabCard Card={card} Search={Search} />}
              </div>
            </WeaDialog> 
            : <WeaDialog
              onCancel={() => cubeViewResource.visible = false}
              url={cubeViewResource.createUrl}
              visible={cubeViewResource.visible}
              hasScroll
              style={{ width: 1200, height: 700 }}
            />
        }
      </div>
    )
  }

}

/*创建面板的提示信息*/
const createTitle = function (titleList) {
  if (Array.isArray(titleList) && titleList.length > 0) {
    return (
      <div className="wea-resource-titletip">
        {titleList.map((meet, idx) => {
          return (
            <div>
              {meet.map((tip) => <div dangerouslySetInnerHTML={{ __html: tip }}></div>)}
              {idx + 1 < titleList.length && <div className="line" />}
            </div>
          );
        })}
      </div>
    );
  }
  return undefined;
}



